package com.example.wl.tiaoyinqi.audio;

import be.tarsos.dsp.AudioDispatcher;
import be.tarsos.dsp.AudioEvent;
import be.tarsos.dsp.io.android.AudioDispatcherFactory;
import be.tarsos.dsp.pitch.PitchDetectionHandler;
import be.tarsos.dsp.pitch.PitchDetectionResult;
import be.tarsos.dsp.pitch.PitchProcessor;

/**
 * Created by wl on 2016/5/25.
 */
public class AudioProcess {

    private static final int SAMPLE_RATE = 44100;
    private static final int BUFFER_SIZE = 16384;

    private AudioDispatcher dispatcher;
    private OnFreqChangedListener onFreqChangedListener;

    public AudioProcess() {
        dispatcher = AudioDispatcherFactory
                .fromDefaultMicrophone(SAMPLE_RATE, BUFFER_SIZE, BUFFER_SIZE / 2);
        dispatcher.addAudioProcessor(new PitchProcessor(
                PitchProcessor.PitchEstimationAlgorithm.FFT_YIN,
                SAMPLE_RATE,
                BUFFER_SIZE,
                new PitchDetectionHandler() {
            @Override
            public void handlePitch(PitchDetectionResult pitchDetectionResult, AudioEvent audioEvent) {
                onFreqChangedListener.onFreqChanged(pitchDetectionResult.getPitch());
            }
        }));
    }

    public void start() {
        new Thread(dispatcher).start();
    }

    public void stop() {
        dispatcher.stop();
    }

    public interface OnFreqChangedListener {
        void onFreqChanged(float freq);
    }

    public void setOnFreqChangedListener(OnFreqChangedListener listener) {
        this.onFreqChangedListener = listener;
    }
}
